package hotel.meituan.oversea.biz.controller;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.constant.enums.MtGoodsEnums;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.SendUtils;
import hotel.base.oversea.utils.StringUtil;
import hotel.meituan.oversea.api.entity.MtNotifyShortLog;
import hotel.meituan.oversea.biz.mapper.MtNotifyShortLogMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 美团异步通知队列日志Controller
 * @author qiuyy
 * @date 2020-05-15
 */
@Slf4j
@RestController
@RequestMapping("/mtNotifyShortLog")
@Api(value = "MtNotifyShortLogController", tags = {"美团异步通知队列日志"})
public class MtNotifyShortLogController {
    @Autowired
    MtNotifyShortLogMapper mtNotifyShortLogMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/popSaveLog")
    @ApiOperation(value = "从队列中获取数据保存操作日志",notes="必须经过auth授权")
    public Result popSaveLog(@RequestBody Map map){
        MtNotifyShortLog mtNotifyShortLog = new MtNotifyShortLog();
        mtNotifyShortLog.setId(StringUtil.getUUID());
        mtNotifyShortLog.setCreateTime(new Date());
        mtNotifyShortLog.setSwHotelId((String)map.get("hotelId"));//携程母酒店id
        mtNotifyShortLog.setMtHotelId((String)map.get("mtHotelId"));//对应的美团酒店id
        mtNotifyShortLog.setTimestamp((String)map.get("timestamp"));//时间戳
        mtNotifyShortLog.setOprate(MtGoodsEnums.goodsChangeType.POP.getCode());//0 push 往队列增加变更数据  1 pop 从队列中获取数据
        mtNotifyShortLog.setSource(MtGoodsEnums.goodsChangeSource.SWITCHS_PUSH.getCode()); // 10 异步价格  11 主动查询价格 20 异步房态  21 主动查询房态 30 携程推送成功数据

        mtNotifyShortLogMapper.insert(mtNotifyShortLog);
        return  new Result();
    }

    @PostMapping("/checkMiss")
    @ApiOperation(value = "查询校验没有被推送给第三方携程的变化数据",notes="必须经过auth授权")
    public Result checkMiss(){
        //携程处理变动数据可能需要半分钟，所以往前查询40秒之前数据 到 三分钟
        Integer time1 = redisTemplate.opsForValue().get("checkMiss_end")==null?40000: (Integer) redisTemplate.opsForValue().get("checkMiss_end");
        Integer time2 = redisTemplate.opsForValue().get("checkMiss_start")==null?180000: (Integer) redisTemplate.opsForValue().get("checkMiss_start");
        Date end = DateUtil.addMilliSecond(new Date(),-time1);//最近的时间
        Date start = DateUtil.addMilliSecond(new Date(),-time2);//最远的时间
        Map map = new HashMap();
        map.put("startTime",DateUtil.formatDate(start,"yyyy-MM-dd HH:mm:ss"));
        map.put("endTime",DateUtil.formatDate(end,"yyyy-MM-dd HH:mm:ss"));
        List<MtNotifyShortLog> list = mtNotifyShortLogMapper.checkMiss(map);
        log.info("MtNotifyShortLogController 查询校验没有被推送给第三方携程的变化数据 checkMiss={}", JSON.toJSONString(list));
        if(null != list && list.size()>0){
            Map<String,String> mapStatus = new HashMap<>();
            Map<String,String> mapPrice = new HashMap<>();
            Map<String,String> mapPriceStatus = new HashMap<>();
            for (MtNotifyShortLog s:list){
                if(null == redisTemplate.opsForValue().get("miss_send_ding_has_"+s.getTimestamp())){
                    redisTemplate.opsForValue().set("miss_send_ding_has_"+s.getTimestamp(),s.getTimestamp(),150, TimeUnit.SECONDS);
                    if(s.getSource()==1){// 0 异步价格  1 异步房态 2 主动查询价格+房态 3 携程推送成功数据
                        mapStatus.put(s.getTimestamp(), JSON.toJSONString(s));
                    }else if(s.getSource()==0){
                        mapPrice.put(s.getTimestamp(), JSON.toJSONString(s));
                    }else if(s.getSource()==2){
                        mapPriceStatus.put(s.getTimestamp(), JSON.toJSONString(s));
                    }
                }
            }
            if(mapStatus.size()>0){
                SendUtils.dingMsg("[MISS-STATUS] 异步'房态变化'数据遗漏，请核实 ", DateUtil.getCurrTime()+"：过去40秒-3分钟内："+mapStatus, MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            }
            if(mapPrice.size()>0){
                SendUtils.dingMsg("[MISS-PRICE] 异步'价格'变化数据遗漏，请核实 ", DateUtil.getCurrTime()+"：过去40秒-3分钟内："+mapPrice, MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            }
            if(mapPriceStatus.size()>0){
                SendUtils.dingMsg("[MISS] '主动查询推送房态价格数据'遗漏，请核实 ", DateUtil.getCurrTime()+"：过去40秒-3分钟内："+mapPriceStatus, MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            }
        }
        return  new Result(list);
    }

    public static void main(String[] args) {


    }

}
